package com.tomecode.tools.maven.settings.gui.frm;

import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.grouplayout.GroupLayout;
import org.eclipse.swt.layout.grouplayout.LayoutStyle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.tomecode.tools.maven.settings.gui.images.ImageFactory;
import com.tomecode.tools.maven.settings.gui.utils.GuiUtils;
import com.tomecode.tools.maven.settings.gui.utils.SWTResourceManager;
import com.tomecode.tools.maven.settings.model.Server;

/**
 * Dialog for editing server
 * 
 * @author Tomas Frastia
 * @see http://www.tomecode.com or
 *      http://code.google.com/p/maven-settings-editor/
 * 
 */
public final class FrmServer extends Dialog {

	private Server newServer;
	private Shell shlServers;
	private Text textServerID;
	private Text textUserName;
	private Text textPassword;
	private Text textPrivateKey;
	private Text textPassphrase;
	private List<Server> listOfServers;
	private Server existsServer;
	private Text textFilePermission;
	private Text textDirectoryPermissions;
	private Text textConfiguration;
	private Label labelWarning;

	/**
	 * Create the dialog.
	 * 
	 * @param parent
	 * @param style
	 */
	public FrmServer(Shell parent, List<Server> listOfServers) {
		super(parent, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
		setText("Servers");
		this.listOfServers = listOfServers;
	}

	/**
	 * Open the dialog.
	 * 
	 * @param existsServer
	 *            if not null then editing selected server
	 * @return the result
	 */
	public final Server open(Server existsServer) {
		createContents(existsServer);
		shlServers.open();
		shlServers.layout();
		Display display = getParent().getDisplay();
		while (!shlServers.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}

		return newServer;
	}

	/**
	 * Create contents of the dialog.
	 */
	private final void createContents(Server existsServer) {
		this.existsServer = existsServer;
		shlServers = new Shell(getParent(), getStyle());
		shlServers.setImage(ImageFactory.MAVEN_SETTINGS_EDITOR_16);
		shlServers.setSize(687, 344);

		Composite composite = new Composite(shlServers, SWT.NONE);
		final Button btnServerSave = new Button(composite, SWT.NONE);

		final Server resultServer;

		if (existsServer == null) {
			resultServer = new Server();
			shlServers.setText("New Server");
			btnServerSave.setEnabled(false);
		} else {
			shlServers.setText("Edit Server");
			resultServer = new Server(existsServer);
			btnServerSave.setEnabled(true);
		}

		GroupLayout gl_shlServers = new GroupLayout(shlServers);
		gl_shlServers.setHorizontalGroup(gl_shlServers.createParallelGroup(GroupLayout.LEADING).add(composite, GroupLayout.DEFAULT_SIZE, 681, Short.MAX_VALUE));
		gl_shlServers.setVerticalGroup(gl_shlServers.createParallelGroup(GroupLayout.TRAILING).add(GroupLayout.LEADING, composite, GroupLayout.DEFAULT_SIZE, 319, Short.MAX_VALUE));

		Group group = new Group(composite, SWT.NONE);

		Label lblPassword = new Label(group, SWT.NONE);
		lblPassword.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));
		lblPassword.setText("Password");

		Label lblPrivateKey = new Label(group, SWT.NONE);
		lblPrivateKey.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));
		lblPrivateKey.setText("Private Key");

		Label lblPassphrase = new Label(group, SWT.NONE);
		lblPassphrase.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));
		lblPassphrase.setText("Passphrase");

		textServerID = new Text(group, SWT.BORDER);
		textServerID.setText(GuiUtils.formateNull(resultServer.getId()));
		textServerID.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultServer.setId(textServerID.getText());

				if (resultServer.getId().trim().length() == 0) {
					labelWarning.setText("Server ID can't be empty");
					btnServerSave.setEnabled(false);
				} else {
					if (existsServerId(resultServer)) {
						labelWarning.setText("Server ID already exists");
						btnServerSave.setEnabled(false);
					} else {
						labelWarning.setText("");
						btnServerSave.setEnabled(true);
					}
				}

			}
		});

		textUserName = new Text(group, SWT.BORDER);
		textUserName.setText(GuiUtils.formateNull(resultServer.getUsername()));
		textUserName.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultServer.setUsername(textUserName.getText());
			}
		});

		textPassword = new Text(group, SWT.BORDER);
		textPassword.setText(GuiUtils.formateNull(resultServer.getPassword()));
		textPassword.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultServer.setPassword(textPassword.getText());
			}
		});

		textPrivateKey = new Text(group, SWT.BORDER);
		textPrivateKey.setText(GuiUtils.formateNull(resultServer.getPrivateKey()));
		textPrivateKey.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultServer.setPrivateKey(textPrivateKey.getText());
			}
		});

		textPassphrase = new Text(group, SWT.BORDER);
		textPassphrase.setText(GuiUtils.formateNull(resultServer.getPassphrase()));
		textPassphrase.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultServer.setPassphrase(textPassphrase.getText());
			}
		});

		Button btnServerCancel = new Button(composite, SWT.NONE);
		btnServerCancel.addSelectionListener(new SelectionAdapter() {
			@Override
			public final void widgetSelected(SelectionEvent e) {
				shlServers.close();
			}
		});
		// if (GuiUtils.isWindows()) {
		// btnServerCancel.setBounds(424, 237, 94, 30);
		// }
		btnServerCancel.setText("Cancel");

		btnServerSave.addSelectionListener(new SelectionAdapter() {
			@Override
			public final void widgetSelected(SelectionEvent e) {
				newServer = resultServer;
				shlServers.close();
			}
		});

		btnServerSave.setText("Save");
		GroupLayout gl_composite = new GroupLayout(composite);
		gl_composite.setHorizontalGroup(gl_composite
				.createParallelGroup(GroupLayout.TRAILING)
				.add(gl_composite.createSequentialGroup().addContainerGap(485, Short.MAX_VALUE).add(btnServerSave, GroupLayout.PREFERRED_SIZE, 94, GroupLayout.PREFERRED_SIZE).addPreferredGap(LayoutStyle.RELATED)
						.add(btnServerCancel, GroupLayout.PREFERRED_SIZE, 94, GroupLayout.PREFERRED_SIZE).addContainerGap()).add(GroupLayout.LEADING, group, GroupLayout.DEFAULT_SIZE, 681, Short.MAX_VALUE));
		gl_composite.setVerticalGroup(gl_composite.createParallelGroup(GroupLayout.LEADING).add(
				gl_composite.createSequentialGroup().add(group, GroupLayout.PREFERRED_SIZE, 267, GroupLayout.PREFERRED_SIZE).add(13).add(gl_composite.createParallelGroup(GroupLayout.TRAILING).add(btnServerCancel).add(btnServerSave)).addContainerGap()));

		Label labelHelpID = new Label(group, SWT.NONE);
		labelHelpID.setToolTipText("A unique identifier");
		labelHelpID.setImage(ImageFactory.HELP);

		Label labelHelpUsername = new Label(group, SWT.NONE);
		labelHelpUsername.setToolTipText("The username used to authenticate.");
		labelHelpUsername.setImage(ImageFactory.HELP);

		Label labelHelpPassword = new Label(group, SWT.NONE);
		labelHelpPassword.setToolTipText("The password used in conjunction with the username to authenticate.");
		labelHelpPassword.setImage(ImageFactory.HELP);

		Label labelHelpPrivateKey = new Label(group, SWT.NONE);
		labelHelpPrivateKey.setToolTipText("The private key location used to authenticate.");
		labelHelpPrivateKey.setImage(ImageFactory.HELP);

		Label labelHelpPassphrase = new Label(group, SWT.NONE);
		labelHelpPassphrase.setToolTipText("The passphrase used in conjunction with the privateKey to authenticate.");
		labelHelpPassphrase.setImage(ImageFactory.HELP);

		Label lblFilePermissions = new Label(group, SWT.NONE);
		lblFilePermissions.setText("File Permissions");
		lblFilePermissions.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));

		textFilePermission = new Text(group, SWT.BORDER);
		textFilePermission.setText(GuiUtils.formateNull(textFilePermission.getText()));
		textFilePermission.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultServer.setFilePermissions(textFilePermission.getText());
			}
		});

		Label labelHelpFilePermissions = new Label(group, SWT.NONE);
		labelHelpFilePermissions.setToolTipText("The permissions for files when they are created.");
		labelHelpFilePermissions.setImage(ImageFactory.HELP);

		Label lblDirectoryPermissions = new Label(group, SWT.NONE);
		lblDirectoryPermissions.setText("Directory Permissions");
		lblDirectoryPermissions.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));

		textDirectoryPermissions = new Text(group, SWT.BORDER);
		textDirectoryPermissions.setText(GuiUtils.formateNull(textDirectoryPermissions.getText()));
		textDirectoryPermissions.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultServer.setDirectoryPermissions(textDirectoryPermissions.getText());
			}
		});

		Label labelHelpDirectoryPermissions = new Label(group, SWT.NONE);
		labelHelpDirectoryPermissions.setToolTipText("The permissions for directories when they are created.");
		labelHelpDirectoryPermissions.setImage(ImageFactory.HELP);

		Label lblUsername = new Label(group, SWT.NONE);
		lblUsername.setText("Username");
		lblUsername.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));

		Label lblId = new Label(group, SWT.NONE);
		lblId.setText("ID");
		lblId.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));

		Label lblConfiguration = new Label(group, SWT.NONE);
		lblConfiguration.setText("Configuration");
		lblConfiguration.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.BOLD));

		textConfiguration = new Text(group, SWT.BORDER);
		textConfiguration.setText(GuiUtils.formateNull(resultServer.getConfiguration()));
		textConfiguration.addKeyListener(new KeyAdapter() {
			@Override
			public final void keyReleased(KeyEvent e) {
				resultServer.setConfiguration(textConfiguration.getText());
			}
		});

		Label labelHelpConfiguration = new Label(group, SWT.NONE);
		labelHelpConfiguration.setToolTipText("Extra configuration for the transport layer.");
		labelHelpConfiguration.setImage(ImageFactory.HELP);

		labelWarning = new Label(group, SWT.NONE);
		labelWarning.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
		GroupLayout gl_group = new GroupLayout(group);
		gl_group.setHorizontalGroup(gl_group.createParallelGroup(GroupLayout.TRAILING).add(
				gl_group.createSequentialGroup()
						.add(gl_group
								.createParallelGroup(GroupLayout.LEADING)
								.add(gl_group
										.createSequentialGroup()
										.add(gl_group
												.createParallelGroup(GroupLayout.LEADING)
												.add(gl_group
														.createSequentialGroup()
														.addContainerGap()
														.add(gl_group.createParallelGroup(GroupLayout.TRAILING, false).add(GroupLayout.LEADING, lblConfiguration, GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)
																.add(GroupLayout.LEADING, lblDirectoryPermissions, GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE).add(GroupLayout.LEADING, lblFilePermissions, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
												.add(gl_group
														.createSequentialGroup()
														.addContainerGap()
														.add(gl_group.createParallelGroup(GroupLayout.TRAILING, false).add(lblPrivateKey, GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE).add(lblPassword, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
																.add(lblPassphrase, GroupLayout.PREFERRED_SIZE, 159, GroupLayout.PREFERRED_SIZE)))
												.add(gl_group.createSequentialGroup().addContainerGap().add(lblUsername, GroupLayout.PREFERRED_SIZE, 142, GroupLayout.PREFERRED_SIZE))
												.add(gl_group.createSequentialGroup().addContainerGap().add(lblId, GroupLayout.PREFERRED_SIZE, 142, GroupLayout.PREFERRED_SIZE)))
										.addPreferredGap(LayoutStyle.RELATED)
										.add(gl_group
												.createParallelGroup(GroupLayout.LEADING)
												.add(gl_group.createParallelGroup(GroupLayout.TRAILING).add(textServerID, GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE).add(textUserName, GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE)
														.add(textPassword, GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE).add(textPrivateKey, GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE).add(textPassphrase, GroupLayout.DEFAULT_SIZE, 497, Short.MAX_VALUE))
												.add(gl_group.createParallelGroup(GroupLayout.LEADING).add(textDirectoryPermissions, GroupLayout.DEFAULT_SIZE, 483, Short.MAX_VALUE).add(textFilePermission, GroupLayout.DEFAULT_SIZE, 483, Short.MAX_VALUE)
														.add(textConfiguration, GroupLayout.DEFAULT_SIZE, 483, Short.MAX_VALUE)))
										.add(18)
										.add(gl_group
												.createParallelGroup(GroupLayout.TRAILING)
												.add(gl_group.createParallelGroup(GroupLayout.LEADING).add(labelHelpID).add(labelHelpUsername).add(labelHelpPassword).add(labelHelpPrivateKey).add(labelHelpPassphrase).add(labelHelpFilePermissions)
														.add(labelHelpDirectoryPermissions)).add(labelHelpConfiguration))).add(gl_group.createSequentialGroup().addContainerGap().add(labelWarning, GroupLayout.DEFAULT_SIZE, 663, Short.MAX_VALUE))).addContainerGap()));
		gl_group.setVerticalGroup(gl_group.createParallelGroup(GroupLayout.LEADING).add(
				gl_group.createSequentialGroup()
						.addContainerGap()
						.add(gl_group.createParallelGroup(GroupLayout.BASELINE).add(textServerID, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).add(labelHelpID).add(lblId))
						.addPreferredGap(LayoutStyle.RELATED)
						.add(gl_group.createParallelGroup(GroupLayout.BASELINE).add(labelHelpUsername).add(textUserName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).add(lblUsername))
						.addPreferredGap(LayoutStyle.RELATED)
						.add(gl_group.createParallelGroup(GroupLayout.BASELINE).add(textPassword, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).add(lblPassword).add(labelHelpPassword))
						.addPreferredGap(LayoutStyle.RELATED)
						.add(gl_group.createParallelGroup(GroupLayout.BASELINE).add(textPrivateKey, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).add(lblPrivateKey).add(labelHelpPrivateKey))
						.add(7)
						.add(gl_group.createParallelGroup(GroupLayout.BASELINE).add(textPassphrase, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).add(lblPassphrase).add(labelHelpPassphrase))
						.addPreferredGap(LayoutStyle.RELATED)
						.add(gl_group.createParallelGroup(GroupLayout.BASELINE).add(textFilePermission, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).add(labelHelpFilePermissions).add(lblFilePermissions))
						.addPreferredGap(LayoutStyle.RELATED)
						.add(gl_group.createParallelGroup(GroupLayout.BASELINE).add(textDirectoryPermissions, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).add(labelHelpDirectoryPermissions).add(lblDirectoryPermissions))
						.addPreferredGap(LayoutStyle.RELATED)
						.add(gl_group.createParallelGroup(GroupLayout.LEADING).add(gl_group.createParallelGroup(GroupLayout.BASELINE).add(textConfiguration, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).add(labelHelpConfiguration))
								.add(lblConfiguration)).add(18).add(labelWarning).add(83)));
		group.setLayout(gl_group);
		composite.setLayout(gl_composite);
		shlServers.setLayout(gl_shlServers);

	}

	private final boolean existsServerId(Server resultServer) {
		for (Server server : listOfServers) {
			if (existsServer != null) {
				if (!existsServer.equals(server)) {
					if (GuiUtils.formateNull(server.getId()).trim().equalsIgnoreCase(resultServer.getId().trim())) {
						return true;
					}
				}
			} else {
				if (GuiUtils.formateNull(server.getId()).trim().equalsIgnoreCase(resultServer.getId().trim())) {
					return true;
				}
			}
		}
		return false;
	}
}
